package controller

import (
	"ginfast/api/mall/dto"
	"ginfast/api/mall/model"
	"ginfast/api/middleware"
	"ginfast/pkg/ginx"
	"ginfast/pkg/orm"
	"ginfast/util"

	"github.com/gin-gonic/gin"
)

// Goods 商品
type Goods struct {
}

// ListHandler 列表
func (Goods) PageHandler(c *gin.Context) {
	var p dto.Where
	ctx, err := ginx.MustBind(c, &p)
	if err != nil {
		return
	}
	var data []model.Goods
	total, _ := p.DbModelWhere(&model.Goods{}).Find(&data)
	ctx.WriteTotal(total, data)
}

// GetHandler 查询
func (Goods) GetHandler(c *gin.Context) {
	util.QueryByID(&model.Goods{}, ginx.JSON(c))
}

// AddHandler 新增
func (Goods) AddHandler(c *gin.Context) {
	var p model.Goods
	//获取参数
	ctx, err := ginx.MustBind(c, &p.GoodsOpt)
	if err != nil {
		return
	}
	if p.OriginalPrice == nil {
		p.OriginalPrice = p.SalesPrice
	}
	if p.PromotionPrice == nil {
		p.PromotionPrice = p.SalesPrice
	}
	p.UpdatedBy = middleware.GetUser(c).UserName
	err = orm.DbCreate(&p)
	ctx.WriteError(err)
}

// UpdateHandler 修改
func (Goods) UpdateHandler(c *gin.Context) {
	var p model.Goods
	//获取参数
	ctx, err := ginx.MustBind(c, &p.GoodsOpt)
	if err != nil {
		return
	}
	p.UpdatedBy = middleware.GetUser(c).UserName
	err = orm.DbUpdateModel(&p)
	ctx.WriteError(err)
}

// DeleteHandler 删除
func (Goods) DeleteHandler(c *gin.Context) {
	util.Deletes(&model.Goods{}, ginx.JSON(c))
}

// goodsspu/shelf?ids=1&shelf=1
// SspuShelfHandler 上架管理

type shelf struct {
	IDS   string `form:"ids"`
	Shelf string `form:"shelf"`
}

func (Goods) ShelfHandler(c *gin.Context) {
	var param shelf
	ctx, err := ginx.MustBind(c, &param)
	if err != nil {
		return
	}
	ids := util.StringSplit(param.IDS, ",")
	err = orm.DbUpdateByID(&model.Goods{}, ids, orm.H{"Shelf": param.Shelf})
	ctx.WriteError(err)
}

func (o Goods) Routers(r *gin.RouterGroup) {
	r.GET("/page", o.PageHandler)
	r.GET("/:id", o.GetHandler)
	r.PUT("", o.UpdateHandler)
	r.POST("", o.AddHandler)
	r.DELETE("", o.DeleteHandler)
	r.PUT("/shelf", o.ShelfHandler)
}
